package org.idea.web.socket.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.idea.web.socket.manager.SocketManager;
import org.idea.web.socket.mq.BroadcastMqProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author linhao
 * @Date created in 3:08 下午 2021/5/8
 */
@RestController
@Slf4j
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate template;
    @Resource
    private BroadcastMqProducer broadcastMqProducer;
    @Resource
    private SocketManager socketManager;

    @MessageMapping("/send-to-user")
    public void sendUser(@RequestBody Map<String, String> map) {
        log.info("map = {}", map);
        broadcastMqProducer.sendWebSocketToUser(map.get("sessionKey"), map.get("message"));
//
//        WebSocketSession webSocketSession = socketManager.get(map.get("name"));
//        if(webSocketSession!=null) {
//            log.info("sessionId = {}",webSocketSession.getId());
//            //指定发送给哪位用户，并且返回消息给到客户端
//            template.convertAndSendToUser(map.get("name"),"/queue/sendUser",map.get("message"));
//        }
    }


    /**
     * 广播通知
     *
     * @param request 消息内容 base64格式
     * @return
     */
    @MessageMapping("/send-all-user")
    @SendTo("/topic/sendTopic")
    public String sendAllUser(HttpServletRequest request) {
        /**
         * 参数转换处理部分省略
         */
        String message = "最终转换成字符串格式接收";
        if(StringUtils.isNotEmpty(message)) {
            log.error("[sendAllUser] message is empty");
            return null;
        }
        broadcastMqProducer.sendWebSocketBroadcastMsg(message);
        return message;
    }



    @GetMapping(value = "/init")
    public String initWebSocketConfig() {
        System.out.println("初始化websocket配置");
        return "success";
    }
}
